package com.banciyuan.bcywebview.biz.apprecommend;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoreApi;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.apprecommend.decoration.AcgDecoration;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.AcgItem;


/**
 * Created by hy on 2015/7/7.
 */
public class RecommendAcgActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView lv;
    private View mProgressbarView;
    private ProgressbarHelper mProgressbarHelper;
    private RequestQueue queue;
    private PopupWindow mPopWindow;
    private ProgressBar pbIng;
    private ImageView ivDone;
    private TextView tvDesc;
    private TextView tvNextStep;
    private RecommendAcgAdapter adapter;
    private TextView select_nums;

    private List<AcgItem> list = new ArrayList<>();
    private boolean haveFans = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hotacg);
        initArgs();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi() {
        lv = (RecyclerView) findViewById(R.id.lv);
        adapter = new RecommendAcgAdapter(this, list, new CheckSelect() {
            @Override
            public void check() {
                checkSelect();
            }
        });
        lv.setAdapter(adapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0) {
                    return 3;
                } else if (position == list.size() + 1) {
                    return 3;
                } else {
                    return 1;
                }
            }
        });
        RecyclerView.ItemAnimator animator = lv.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        lv.setLayoutManager(gridLayoutManager);
        lv.addItemDecoration(new AcgDecoration(this));
        tvNextStep = (TextView) findViewById(R.id.tv_next_step);
        select_nums = (TextView) findViewById(R.id.select_nums);
        select_nums.setVisibility(View.VISIBLE);

    }

    @Override
    protected void initAction() {
        tvNextStep.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + CoserApi.getHotworks();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, RecommendAcgActivity.this)) {
                        JSONObject result = new JSONObject(s);
                        Gson gson = new Gson();
                        List<AcgItem> tempList = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<AcgItem>>() {
                        }.getType());
                        list.addAll(tempList);
                        processStatusData();
                        processData();
                    } else {
                        mProgressbarHelper.onFailed();
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };

        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, onError);
        queue.add(stringRequest);
    }

    private void processStatusData() {
        for (int i = 0; i < list.size(); i++) {
            boolean wf_status = list.get(i).isWf_status();
            if (wf_status) {
                haveFans = true;
                break;
            }
        }
        if (!haveFans && null != list && list.size() >= 3) {
            list.get(0).setWf_status(true);
            list.get(1).setWf_status(true);
            list.get(2).setWf_status(true);
        }
    }

    private void processData() {
        if (null == adapter) {
            adapter = new RecommendAcgAdapter(this, list, new CheckSelect() {
                @Override
                public void check() {
                    checkSelect();
                }
            });
            lv.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        if (!haveFans) {
            Map<String, String> likeMaps = adapter.getLikeMaps();
            if (null != list && list.size() >= 3) {
                likeMaps.put(list.get(0).getId(), "follow");
                likeMaps.put(list.get(1).getId(), "follow");
                likeMaps.put(list.get(2).getId(), "follow");
            }
        }
        checkSelect();
        mProgressbarHelper.onSuccess();
    }

    private void checkSelect() {
        int count = checkSelectNum();
        if (count < 3) {
            tvNextStep.setSelected(false);
        } else {
            tvNextStep.setSelected(true);
        }
        select_nums.setText(String.format(getString(R.string.select_recommend), 3, count));
    }

    private int checkSelectNum() {
        int i = 0;
        for (AcgItem a : list) {
            if (a.isWf_status()) {
                i++;
            }
        }
        return i;
    }

    @Override
    public void onClick(View view) {
        int count = checkSelectNum();
        switch (view.getId()) {
            case R.id.tv_next_step:
                if (count >= 3) {
                    doLikes();
                } else {
                    MyToast.show(RecommendAcgActivity.this, String.format(getString(R.string.select_recommend), 3, count));
                }
                break;
        }
    }

    private void doLikes() {
        Map<String, String> likeMaps = adapter.getLikeMaps();
        if (!likeMaps.keySet().isEmpty()) {
            doPop();
            String url = HttpUtils.BASE_URL + CoreApi.getMultifollow();
            List<BcyPair> paramsList = new ArrayList<>();
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
            paramsList.add(new BcyPair(HttpUtils.UPLOAD_DATA, new Gson().toJson(likeMaps)));
            HashMap<String, String> params = HttpUtils.getData(paramsList);
            Response.Listener<String> onSucc = new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    try {
                        if (StatusCodeUtils.dealStatusCode(s, RecommendAcgActivity.this)) {
                            showcomplate();
                        } else {
                            goNext();
                        }
                    } catch (Exception e) {
                        MyToast.show(RecommendAcgActivity.this, getResources().getString(R.string.bcy_net_error));
                        goNext();
                    }
                }
            };

            Response.ErrorListener onError = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    MyToast.show(RecommendAcgActivity.this, getResources().getString(R.string.bcy_net_error));
                    goNext();
                }
            };

            StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, onError);
            queue.add(stringRequest);
        } else {
            goNext();
        }
    }

    private void showcomplate() {
        pbIng.setVisibility(View.INVISIBLE);
        ivDone.setVisibility(View.VISIBLE);
        tvDesc.setText(getString(R.string.done_success));
        tvNextStep.postDelayed(new Runnable() {
            @Override
            public void run() {
                goNext();
            }
        }, 500);
    }

    private void goNext() {
        if (mPopWindow != null && mPopWindow.isShowing() && !RecommendAcgActivity.this.isFinishing()) {
            mPopWindow.dismiss();
        }
        gotoUtil.gotoAct(RecommendAcgActivity.this, RecommendNewTagActivity.class);
        finish();
    }

    private void doPop() {
        View contentView = View.inflate(this, R.layout.pop_mark_acg, null);
        mPopWindow = new PopupWindow(contentView,
                -1, -1,
                true);
        mPopWindow.setContentView(contentView);
        pbIng = (ProgressBar) contentView.findViewById(R.id.pb_ing);
        ivDone = (ImageView) contentView.findViewById(R.id.iv_done);
        tvDesc = (TextView) contentView.findViewById(R.id.tv_desc);
        mPopWindow.setOutsideTouchable(false);
        mPopWindow.showAtLocation(tvNextStep, Gravity.LEFT + Gravity.TOP,
                0, 0);
    }

    public interface CheckSelect {
        void check();
    }

    @Override
    public void onBackPressed() {

    }
}
